package cn;

import javassist.*;

/**
 * javassist使用简单示例
 */
public class CreatePerson {

    private static void createPerson() throws Exception{
        ClassPool pool = ClassPool.getDefault();
        //创建一个空类
        CtClass personClass = pool.makeClass("cn.Person");
        //新增一个字段 private String name
        CtField nameField = new CtField(pool.get("java.lang.String"), "name", personClass);
        nameField.setModifiers(Modifier.PRIVATE);
        //给name字段初始化一个值xiaoming
        personClass.addField(nameField,CtField.Initializer.constant("xiaoming"));
        //生成get和set方法
        personClass.addMethod(CtNewMethod.setter("setName",nameField));
        personClass.addMethod(CtNewMethod.getter("getName",nameField));
        //添加构造函数
        CtConstructor constructor = new CtConstructor(new CtClass[]{}, personClass);
        constructor.setBody("{name=\"xiaoming\";}");
        personClass.addConstructor(constructor);
        constructor=new CtConstructor(new CtClass[]{pool.get("java.lang.String")},personClass);
        // $0=this / $1,$2,$3... 代表方法参数
        constructor.setBody("{$0.name = $1;}");
        personClass.addConstructor(constructor);
        //  创建一个名为printName方法，无参数，无返回值，输出name值
        CtMethod printMethod = new CtMethod(CtClass.voidType, "printName", new CtClass[]{}, personClass);
        printMethod.setModifiers(Modifier.PUBLIC);
        printMethod.setBody("{System.out.println(name);}");
        personClass.addMethod(printMethod);
        personClass.writeFile("D:\\workspace\\unit\\unit\\target\\classes\\cn");
        //从内存中释放
        personClass.detach();

    }

    public static void main(String[] args) throws Exception{
        createPerson();
    }
}
